package field;

import java.util.ArrayList;
import cell.Cell;

public class Field {
	private static final Location[] adjacent = {
			new Location(-1,-1), new Location(-1,0), new Location(-1,1),
			new Location(0,-1), new Location(0,0), new Location(0,1),
			new Location(1,-1), new Location(1,0), new Location(1,1)
	};
	private int width093121121;
	private int height093121121;
	private Cell[][] field093121121;

	public Field(int width093121121, int height093121121){
		this.width093121121 = width093121121;
		this.height093121121 = height093121121;
		field093121121 = new Cell[height093121121][width093121121];
	}

	public int getWidth093121121(){
		return width093121121;
	}

	public int getHeight093121121(){
		return height093121121;
	}

	public Cell place(int row, int col, Cell o){
		Cell ret = field093121121[row][col];
		field093121121[row][col] = o;
		return ret;
	}

	public Cell get(int row, int col){
		return field093121121[row][col];
	}

	public Cell remove(int row, int col){
		Cell ret = field093121121[row][col];
		field093121121[row][col] = null;
		return ret;
	}

	public void remove(Cell cell){
		for (int row = 0; row < height093121121; row++){
			for (int col = 0; col < width093121121; col++){
				if (field093121121[row][col] == cell){
					field093121121[row][col] = null;
					break;
				}
			}
		}
	}

	public void clear(){
		for (int i = 0; i < height093121121; i++){
			for (int j = 0; j < width093121121; j++){
				field093121121[i][j] = null;
			}
		}
	}

	public void move(int row, int col, Location loc){
		field093121121[loc.getRow()][loc.getCol()] = field093121121[row][col];
		remove(row, col);
	}

	public Cell[] getNeighbour(int row, int col){
		ArrayList<Cell> neighbour = new ArrayList<Cell>();
		for (int i = -1; i < 2; i++){
			for (int j = -1; j < 2; j++){
				int r = row + i;
				int c = col + j;
				if (!(i == 0 && j == 0) && r < width093121121 && c < height093121121 && r > -1 && c > -1){
					neighbour.add(field093121121[r][c]);
				}
			}
		}
		return neighbour.toArray(new Cell[neighbour.size()]);
	}

	public Location[] getFreeNeighbour(int row, int col){
		ArrayList<Location> list = new ArrayList<Location>();
		for (Location loc : adjacent){
			int r = row + loc.getRow();
			int c = col + loc.getCol();
			if (r > -1 && r < height093121121 && c > -1 && c < width093121121 && field093121121[r][c] == null){
				list.add(new Location(r, c));
			}
		}
		return list.toArray(new Location[list.size()]);
	}

	public boolean placeRandomAdj(int row, int col, Cell cell){
		boolean ret = false;
		Location[] freeAdj = getFreeNeighbour(row, col);
		if (freeAdj.length > 0){
			int idx = (int)(Math.random() * freeAdj.length);
			field093121121[freeAdj[idx].getRow()][freeAdj[idx].getCol()] = cell;
			ret = true;
		}
		return ret;
	}
}
